﻿using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using AutoMapper;
using PagedList;
using SIG.Service;
using SIG.Model;
using System;

using SIG.WebMVC.Filters;
using SIG.Infrastructure.Configs;
using SIG.Model.Enums;
using SIG.ViewModel;
using SIG.Infrastructure.Extensions;
using SIG.Model.Articles;
using SIG.ViewModel.Admin.Articles;
using System.Xml.Linq;
using SIG.Infrastructure.Helper;
using SIG.Resources.Admin;
using SIG.InputModel.Admin.Articles;

namespace SIG.WebMVC.Areas.Admin.Controllers
{
    [SIGAuth]
    public class ArticleController : BaseController
    {
        private readonly IArticleCategoryService _categoryService;
        private readonly IArticleService _articleService;
        private readonly IPageMetaService _pageMetaService;
        private readonly IMapper _mapper;

        public ArticleController(IArticleCategoryService categoryService, IArticleService articleService, IPageMetaService pageMetaService, IMapper mapper)
        {
            _categoryService = categoryService;
            _articleService = articleService;
            _pageMetaService = pageMetaService;
            _mapper = mapper;


        }
        #region 新闻


        [HttpGet]
        public ActionResult Index(int? page, int? categoryId, string Keyword)
        {

            var articleListVM = new ArticleListVM();

            articleListVM.CategoryId = categoryId ?? 0;
            articleListVM.PageIndex = (page ?? 1) - 1;
            articleListVM.PageSize = SettingsManager.Article.PageSize;
            articleListVM.Keyword = Keyword;

            int count;
            var articles = _articleService.GetPagedElements(articleListVM.PageIndex, articleListVM.PageSize, articleListVM.Keyword, articleListVM.CategoryId, out count);

            var articleDtos = _mapper.Map<IEnumerable<Article>, IEnumerable<ArticleVM>>(articles.AsEnumerable());

            //   articleListVM.Articles = articleDtos;
            articleListVM.TotalCount = count;

            var categoryList = _categoryService.GetAll().OrderByDescending(c => c.Importance).ToList();
            var categories = new SelectList(categoryList, "Id", "Title");
            ViewBag.Categories = categories;

            articleListVM.Articles = new StaticPagedList<ArticleVM>(articleDtos, articleListVM.PageIndex + 1, articleListVM.PageSize, articleListVM.TotalCount);
            //  ViewBag.OnePageOfArticles = articlesAsIPagedList;

            ViewBag.PageSizes = new SelectList(Site.PageSizes());

            return View(articleListVM);

        }


        [HttpPost]
        public JsonResult PageSizeSet(int pageSize)
        {
            try
            {
                var xmlFile = Server.MapPath("~/Config/ArticleSettings.config");
                XDocument doc = XDocument.Load(xmlFile);

                var item = doc.Descendants("Settings").FirstOrDefault();
                item.Element("PageSize").SetValue(pageSize);
                doc.Save(xmlFile);

                return Json(AR, JsonRequestBehavior.DenyGet);
            }
            catch (Exception ex)
            {
                AR.Setfailure(ex.Message);
                return Json(AR, JsonRequestBehavior.DenyGet);
            }
        }


        public ActionResult Add()
        {
            var article = new ArticleIM { Active = true };

            var categorys = _categoryService.GetAll().OrderByDescending(m => m.Importance).ToList();
            var lCategorys = new SelectList(categorys, "Id", "Title");

            ViewBag.Categories = lCategorys;
            return View(article);
        }


        [HttpPost]
        [ValidateAntiForgeryToken]
        public JsonResult Add(ArticleIM article)
        {
            if (!ModelState.IsValid)
            {
                AR.Setfailure(GetModelErrorMessage());
                return Json(AR, JsonRequestBehavior.DenyGet);
            }

            try
            {

                var newArticle = _mapper.Map<ArticleIM, Article>(article);
                _articleService.Create(newArticle);

                if (!string.IsNullOrEmpty(article.Keywords) || !string.IsNullOrEmpty(article.SEODescription))
                {
                    var pageMeta = new PageMeta()
                    {
                        ObjectId = newArticle.Id,
                        Keyword = article.Keywords,
                        Description = article.SEODescription,
                        ModelType = ModelType.ARTICLE
                    };
                    _pageMetaService.Create(pageMeta);
                }

                AR.SetSuccess(String.Format(Messages.AlertCreateSuccess, EntityNames.Article));
                return Json(AR, JsonRequestBehavior.DenyGet);

            }
            catch (Exception er)
            {
                AR.Setfailure(er.Message);
                return Json(AR, JsonRequestBehavior.DenyGet);
            }


        }

        [HttpGet]
        public ActionResult Edit(int Id)
        {
            var vArticle = _articleService.GetById(Id);
            if (vArticle == null)
            {
                AR.Setfailure(Messages.HttpNotFound);
                return Json(AR, JsonRequestBehavior.AllowGet);
            }


            var editArticle = _mapper.Map<Article, ArticleIM>(vArticle);

            var pageMeta = _pageMetaService.GetPageMeta(ModelType.ARTICLE, editArticle.Id);
            if (pageMeta != null)
            {
                editArticle.Keywords = pageMeta.Keyword;
                editArticle.SEODescription = pageMeta.Description;
            }

            var categorys = _categoryService.GetAll().OrderByDescending(m => m.Importance).ToList();
            var lCategorys = new SelectList(categorys, "Id", "Title");

            ViewBag.Categories = lCategorys;

            return View(editArticle);


        }

        [HttpPost]
        [ValidateInput(false)]
        [ValidateAntiForgeryToken]
        public JsonResult Edit(ArticleIM article)
        {
            if (!ModelState.IsValid)
            {
                AR.Setfailure(GetModelErrorMessage());
                return Json(AR, JsonRequestBehavior.DenyGet);
            }

            try
            {
                var editArticle = _mapper.Map<ArticleIM, Article>(article);
                _articleService.Update(editArticle);

                var pageMeta = _pageMetaService.GetPageMeta(ModelType.ARTICLE, editArticle.Id);
                pageMeta = pageMeta ?? new PageMeta();


                if (!string.IsNullOrEmpty(article.Keywords) || !string.IsNullOrEmpty(article.SEODescription))
                {

                    pageMeta.ObjectId = article.Id;
                    pageMeta.Keyword = article.Keywords;
                    pageMeta.Description = article.SEODescription;
                    pageMeta.ModelType = ModelType.ARTICLE;

                    if (pageMeta.Id > 0)
                    {
                        _pageMetaService.Update(pageMeta);
                    }
                    else
                    {
                        _pageMetaService.Create(pageMeta);
                    }
                }

                AR.SetSuccess(String.Format(Messages.AlertUpdateSuccess, EntityNames.Article));
                return Json(AR, JsonRequestBehavior.DenyGet);

            }
            catch (Exception er)
            {
                AR.Setfailure(er.Message);
                return Json(AR, JsonRequestBehavior.DenyGet);
            }


        }


        [HttpPost]
        [ValidateAntiForgeryToken]
        public JsonResult Active(int id)
        {

            Article vArticle = _articleService.GetById(id);

            try
            {
                vArticle.Active = !vArticle.Active;
                _articleService.Update(vArticle);

                var vm = _mapper.Map<ArticleVM>(vArticle);

                AR.Data = RenderPartialViewToString("_ArticleItem", vm);
                AR.SetSuccess(String.Format(Messages.AlertUpdateSuccess, EntityNames.Article));
                return Json(AR, JsonRequestBehavior.DenyGet);

            }
            catch (Exception ex)
            {
                AR.Setfailure(ex.Message);
                return Json(AR, JsonRequestBehavior.DenyGet);
            }

        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public JsonResult Recommend(int id)
        {

            Article vArticle = _articleService.GetById(id);

            try
            {
                vArticle.Recommend = !vArticle.Recommend;
                _articleService.Update(vArticle);

                var vm = _mapper.Map<ArticleVM>(vArticle);
                AR.Data = RenderPartialViewToString("_ArticleItem", vm);
                AR.SetSuccess(String.Format(Messages.AlertUpdateSuccess, EntityNames.Article));
                return Json(AR, JsonRequestBehavior.DenyGet);

            }
            catch (Exception ex)
            {
                AR.Setfailure(ex.Message);
                return Json(AR, JsonRequestBehavior.DenyGet);
            }

        }


        [HttpPost]
        [ValidateAntiForgeryToken]
        public JsonResult Delete(int id)
        {

            Article vArticle = _articleService.GetById(id);

            if (vArticle == null)
            {
                AR.Setfailure(Messages.HttpNotFound);
                return Json(AR, JsonRequestBehavior.DenyGet);
            }

            _articleService.Delete(vArticle);

            AR.SetSuccess(String.Format(Messages.AlertDeleteSuccess, EntityNames.Article));
            return Json(AR, JsonRequestBehavior.DenyGet);

        }

        #endregion


    }
}
